package drds.plus.parser.abstract_syntax_tree.expression.primary.misc;

import drds.plus.parser.abstract_syntax_tree.expression.PrimaryExpression;
import drds.plus.parser.visitor.Visitor;

public class Identifier extends PrimaryExpression {
    protected final String text;
    /**
     * null if no parent
     */
    protected Identifier parent;

    public Identifier(Identifier parent, String text) {
        this.parent = parent;
        this.text = text.toLowerCase();// 统一变成小写
    }

    private static boolean objEquals(Object obj, Object obj2) {
        if (obj == obj2)
            return true;
        if (obj == null)
            return obj2 == null;
        return obj.equals(obj2);
    }

    public Identifier getParent() {
        return parent;
    }

    public void setParent(Identifier parent) {
        this.parent = parent;
    }

    public String getText() {
        return text;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("标识符为:");
        if (parent != null) {
            sb.append(parent).append('.');
        }
        return sb.append(text).toString();
    }

    public int hashCode() {
        final int constant = 37;
        int hash = 17;
        if (parent == null) {
            hash += constant;
        } else {
            hash = hash * constant + parent.hashCode();
        }
        if (text == null) {
            hash += constant;
        } else {
            hash = hash * constant + text.hashCode();
        }
        return hash;
    }

    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (obj instanceof Identifier) {
            Identifier that = (Identifier) obj;
            return objEquals(this.parent, that.parent) && objEquals(this.text, that.text);
        }
        return false;
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}
